package xuanmu.office.excel.data.generator.dao;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import xuanmu.office.excel.data.generator.entity.Route;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Repository
public final class RouteDao {

    @Value("${custom.route-info.src}")
    private String csvFilePath;

    public List<Route> list() {
        List<Route> routeList = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(new FileInputStream(csvFilePath), "GBK"))) {
//            try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] values = line.split(",");
                if (values.length != 3) {
                    continue; // 如果数组长度不是3，则跳过该行
                }
                String departure = values[0].substring(0, values[0].indexOf("-"));
                String destination = values[0].substring(values[0].indexOf("-") + 1);
                Route route = new Route(departure, destination, Integer.parseInt(values[1].trim()), Integer.parseInt(values[2].trim()));
                routeList.add(route);
            }
        } catch (IOException e) {
            System.err.println("【错误】无法读取【路线信息配置文件】：" + csvFilePath);
            System.err.println("【提示】请检查【application.properties】中的配置，确保文件存在且可读");
            System.exit(0);
        }
        System.out.println("【系统】读取到【" + routeList.size() + "】条线路信息，数据来源：" + csvFilePath);
        if (routeList.size() == 0) {
            System.err.println("【错误】无法读取到有效的路线信息，请检查配置！");
            System.exit(0);
        }
        return routeList;
    }

}